//
//  PPYSigninView.swift
//  PanPanYan
//
//  Created by 向攀 on 2018/2/5.
//  Copyright © 2018年 向攀. All rights reserved.
//

import UIKit
import MBProgressHUD



@objc protocol PPYSigninViewDelegate: NSObjectProtocol {
    @objc func signinViewSigninAction(signView: PPYSigninView, mobilePhone: String, password: String)
    @objc func signinViewSignupAction(signView: PPYSigninView, mobilePhone: String, verifyCode: String)
}

class PPYSigninView: UIView {
    weak var delegate: PPYSigninViewDelegate?
    
    var currentLoginType = PPYLoginType.password
    
    
    init(frame: CGRect, delegate: PPYSigninViewDelegate) {
        super.init(frame: frame)
        self.delegate = delegate
        setupUI()
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    func setupUI() -> Void {
        setupPasswordSigninView()
        setupVerifySigninView()
        setupLoginButton()
        
        accountVerifyInputView.superview?.isHidden = true
        
//        let lastUserMobile = PPYLogedInUserTool.lastLogInTypeAndUserMobile()
//        if lastUserMobile != nil {
//            if lastUserMobile!.type == .password {
//                accountPasswordInputView.setLastLogedInUserMobile(mobile: lastUserMobile!.mobile)
//                return
//            }
//            accountVerifyInputView.setLastLogedInUserMobile(mobile: lastUserMobile!.mobile)
//            changeToVerifyCodeLoginType()
//        }
        if PPYLogedInUserTool.currentLogedInUser.logedInType == .password {
            accountPasswordInputView.setLastLogedInUserMobile(mobile: PPYLogedInUserTool.currentLogedInUser.userMobilePhone)
        } else if PPYLogedInUserTool.currentLogedInUser.logedInType == .verifyCode {
            accountVerifyInputView.setLastLogedInUserMobile(mobile: PPYLogedInUserTool.currentLogedInUser.userMobilePhone)
            changeToVerifyCodeLoginType()
        }
    }
    
    /**
     * desp: 初始化并布局账号登录和验证码登录视图,每一个视图都在一个UIview的容器视图里面,容器视图再添加到这个大视图下(和登录按钮平级),显示其中一个,另一个的容器视图设置为hidden
     */
    func setupPasswordSigninView() -> Void {
        let containerView = UIView(frame: CGRect(x: 0, y: 0, width: bounds.width, height: 130))
        addSubview(containerView)
        containerView.center.x = bounds.size.width * 0.5
        
        containerView.addSubview(accountPasswordInputView)
        accountPasswordInputView.center.x = containerView.bounds.size.width * 0.5
        
        let buttonWidth: CGFloat = 90
        let button = UIButton(frame: CGRect(x: accountPasswordInputView.frame.maxX - buttonWidth, y: accountPasswordInputView.frame.maxY, width: buttonWidth, height: 25))

        button.contentEdgeInsets = UIEdgeInsets(top: 3, left: 0, bottom: 10, right: 12)
        button.setTitle("验证码登录", for: .normal)
        button.setImage(UIImage(named: "arrow_right_white"), for: .normal)
        let imageWidth: CGFloat = 25
        button.imageEdgeInsets = UIEdgeInsets(top: 0, left: buttonWidth - imageWidth, bottom: 0, right: 0)
        button.titleEdgeInsets = UIEdgeInsets(top: 0, left: -buttonWidth - 2, bottom: 0, right: 0)
        button.setTitleColor(UIColor.white, for: .normal)
        button.titleLabel?.font = PPYGlobalConstants.fontLevel6
        
        button.addTarget(self, action: #selector(changeToVerifyCodeLoginType), for: .touchUpInside)
        containerView.addSubview(button)
        
        let tipLabel = UILabel(frame: CGRect(x: accountPasswordInputView.frame.origin.x + 10, y: accountPasswordInputView.frame.maxY, width: accountPasswordInputView.frame.size.width - button.bounds.size.width - 10, height: 12))
        tipLabel.textColor = UIColor.white
        tipLabel.font = UIFont.systemFont(ofSize: PPYDynamicLayout.flexibleWidth(width: 9))
        tipLabel.text = "新用户请切换到验证码注册登陆"
        containerView.addSubview(tipLabel)
        tipLabel.center.y = button.center.y - 3.5
    }
    
    func setupVerifySigninView() -> Void {
        let containerView = UIView(frame: CGRect(x: 0, y: 0, width: bounds.width, height: 130))
        addSubview(containerView)
        containerView.center.x = bounds.size.width * 0.5
        
        containerView.addSubview(accountVerifyInputView)
        accountVerifyInputView.center.x = containerView.bounds.size.width * 0.5
        
        let buttonWidth: CGFloat = 90
        let button = UIButton(frame: CGRect(x: accountVerifyInputView.frame.origin.x, y: accountVerifyInputView.frame.maxY, width: buttonWidth, height: 25))

        button.contentEdgeInsets = UIEdgeInsets(top: 3, left: 12, bottom: 10, right: 0)
        button.setTitle("密码登录", for: .normal)
        button.setImage(UIImage(named: "arrow_left_white"), for: .normal)
        let imageWidth: CGFloat = 25
        button.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: buttonWidth - imageWidth)
        button.titleEdgeInsets = UIEdgeInsets(top: 0, left: -(buttonWidth), bottom: 0, right: 0)
        button.setTitleColor(UIColor.white, for: .normal)
        button.titleLabel?.font = PPYGlobalConstants.fontLevel6
        
        button.addTarget(self, action: #selector(changeToPasswordLoginType), for: .touchUpInside)
        containerView.addSubview(button)
        
        let tipLabel = UILabel(frame: CGRect(x: button.frame.maxX, y: accountVerifyInputView.frame.maxY, width: accountVerifyInputView.frame.maxX - button.frame.maxX - 10, height: 12))
        tipLabel.textColor = UIColor.white
        tipLabel.font = UIFont.systemFont(ofSize: PPYDynamicLayout.flexibleWidth(width: 9))
        tipLabel.textAlignment = .right
        tipLabel.text = "未注册用户手机验证后自动注册并登陆"
        containerView.addSubview(tipLabel)
        tipLabel.center.y = button.center.y - 3.5
    }
    
    private func setupLoginButton() -> Void {
        let topView = accountVerifyInputView.superview!
        
        loginButton.frame = CGRect(x: 100, y: topView.frame.maxY + 35, width: 100, height: 36)
        loginButton.center.x = topView.center.x
    }
    
    //MARK: - getter
    private lazy var accountPasswordInputView: PPYSigninInfoView = {
        let object = PPYSigninInfoView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH - 100, height: 0), type: .password, loginInfoChangedHandler: { (isCompleted) in
            self.loginButton.isEnabled = isCompleted
        })
        return object
    }()
    private lazy var accountVerifyInputView: PPYSigninInfoView = {
        let object = PPYSigninInfoView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH - 100, height: 0), type: .verifyCode, loginInfoChangedHandler: { (isCompleted) in
            self.loginButton.isEnabled = isCompleted
        })
        return object
    }()
    
    private lazy var loginButton: UIButton = {
        let button = UIButton()
        button.layer.cornerRadius = 16
        button.clipsToBounds = true
        button.layer.borderWidth = 2
        button.layer.borderColor = UIColor.white.cgColor
        
        button.titleLabel?.font = PPYGlobalConstants.fontLevel1
        
        button.setBackgroundImage(UIImage(named: "color_image_clear"), for: .disabled)
        button.setBackgroundImage(UIImage(named: "color_image_white"), for: .normal)
        button.setBackgroundImage(UIImage(named: "color_image_white"), for: .highlighted)
        button.setTitleColor(UIColor.white, for: .disabled)
        button.setTitleColor(ColorLoginBackgroundGreen, for: .normal)
        button.setTitleColor(ColorLoginBackgroundGreen, for: .highlighted)
        button.setTitle("登 录", for: .normal)
        button.addTarget(self, action: #selector(loginButtonClicked(button:)), for: .touchUpInside)
        
        button.isEnabled = false
        
        self.addSubview(button)
        return button
    }()
    
    //MARK: - event response
    @objc private func changeToVerifyCodeLoginType() -> Void {
        endEditing(true)
        accountPasswordInputView.superview?.isHidden = true
        accountVerifyInputView.superview?.isHidden = false
        currentLoginType = .verifyCode
        loginButton.isEnabled = accountVerifyInputView.isInfomationCompleted()
    }
    
    @objc private func changeToPasswordLoginType() -> Void {
        endEditing(true)
        accountPasswordInputView.superview?.isHidden = false
        accountVerifyInputView.superview?.isHidden = true
        currentLoginType = .password
        loginButton.isEnabled = accountPasswordInputView.isInfomationCompleted()
    }
    
    @objc private func loginButtonClicked(button: UIButton) -> Void {
        
        let currentLoginInfoView = (currentLoginType == .password) ? accountPasswordInputView : accountVerifyInputView
        
        if let siginSuperView = currentLoginInfoView.superview?.subviews {
            
            for subView in siginSuperView {
                if subView != currentLoginInfoView {
                    subView.isHidden = true
                }
            }
        }
        
        currentLoginInfoView.loginAnimation() //登陆动画
        
        loginAction()
    }
    
    /**
     * desp: 登录失败,重新回到登录信息输入界面
     */
    func loginFailed() -> Void {
//        if currentLoginType == .password {
//            accountPasswordInputView.loginFailedAnimation()
//            return
//        }
//        accountVerifyInputView.loginFailedAnimation()
        let currentLoginInfoView = (currentLoginType == .password) ? accountPasswordInputView : accountVerifyInputView
        currentLoginInfoView.loginFailedAnimation()
        if let siginSuperView = currentLoginInfoView.superview?.subviews {
            for subView in siginSuperView {
                if subView != currentLoginInfoView {
                    subView.isHidden = false
                    subView.alpha = 0.01
                }
            }
        }
        
        UIView.animate(withDuration: 0.25, delay: 0.5, options: UIView.AnimationOptions(rawValue: 0), animations: {
            
            if let siginSuperView = currentLoginInfoView.superview?.subviews {
                for subView in siginSuperView {
                    subView.alpha = 1.0
                }
            }
        }, completion: nil)
    }
    
    private func loginAction() -> Void {
        
        if currentLoginType == .password {
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
                let loginInfo = self.accountPasswordInputView.getLoginInfo()
                if (loginInfo != nil) && (self.self.delegate != nil) && (self.delegate?.responds(to: #selector(PPYSigninViewDelegate.signinViewSigninAction(signView:mobilePhone:password:))))! {
                    self.delegate?.signinViewSigninAction(signView: self, mobilePhone: loginInfo!.mobile, password: loginInfo!.validateInfo)
                }
            }
        } else {
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
                let loginInfo = self.accountVerifyInputView.getLoginInfo()
                if (loginInfo != nil) && (self.self.delegate != nil) && (self.delegate?.responds(to: #selector(PPYSigninViewDelegate.signinViewSignupAction(signView:mobilePhone:verifyCode:))))! {
                    self.delegate?.signinViewSignupAction(signView: self, mobilePhone: loginInfo!.mobile, verifyCode: loginInfo!.validateInfo)
                }
            }
        }
    }
}
